import type {Menus, Menu, MenuHandler} from './index.types'
import read from './ready'

const ID_PREF = 'ecplugin-ecology-chrome-extension-menus_'

const root: Menu = {
    id: ID_PREF + 'root',
    title: 'Ecplugin',
    onClick: () => undefined,
    children: [],
}
const handlers: MenuHandler[] = []
const Menus: Menus = {
    root: root,
    handlers: handlers,
    register: (fullTitle, onClick) => {
        if (fullTitle) {

            let parent = root
            let titles = undefined
            fullTitle.split('/').forEach(title => {
                titles = titles ? [titles, title].join('/') : title
                const id = ID_PREF + titles.split('').reduce((pre, curr) => pre + curr.charCodeAt(0).toString(16), '')
                let menu = parent.children.find(it => it.id === id)
                if (!menu) {
                    menu = {
                        id: id,
                        title: title,
                        onClick: onClick,
                        children: [],
                    }
                    parent.children.push(menu)
                }
                parent = menu
            })

            handlers.push({
                id: ID_PREF + fullTitle.split('').reduce((pre, curr) => pre + curr.charCodeAt(0).toString(16), ''),
                function: onClick,
            })

            window.sessionStorage.setItem(
                'ecplugin-ecology-chrome-extension-menu',
                JSON.stringify(root)
            );
        }
    }
}

read(() => {
    root?.children?.splice?.(0, root?.children?.length)
    window.sessionStorage.removeItem('ecplugin-ecology-chrome-extension-menu')
})

window.addEventListener?.('message', (event) => {
    const menuId = event?.data ?? ''
    if (menuId.startsWith?.(ID_PREF)) {
        const handler = handlers.find(it => it.id === menuId)
        handler?.function?.()
    }
})

export default Menus